from django.contrib.auth import login
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views import View
from libs.QQLogin.QQLoginTool import OAuthQQ
from meiduo_mall import settings
from utils.response_code import RETCODE
from .utils import encrpty_openid, check_access_token
from .models import OAuthQQUser

# Create your views here.


class OAuthQQUrlView(View):
    """返回QQ登陆的url"""

    def get(self, request):
        # next表示从哪个页面进入到的登录页面，将来登录成功后，就自动回到那个页面
        next = request.GET.get('next')

        # 获取QQ登录页面网址
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)
        login_url = oauth.get_qq_url()

        return JsonResponse({'code': RETCODE.OK,
                             'errmsg': 'OK',
                             'login_url': login_url})


class OAuthQQUserView(View):
    """返回QQ登陆成功后的页面"""

    def get(self, request):
        """QQ登陆，已经绑定过个人信息"""
        code = request.GET.get('code')
        if not code:
            return render(request, 'oauth_callback.html', context={'account_errmsg': '没有获取到所需参数'})
            # 创建工具对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        # 使用code向QQ服务器请求access_token
        token = oauth.get_access_token(code)
        # 使用access_token向QQ服务器请求openid
        openid = oauth.get_open_id(token)

        # 通过openid查询用户是否存在
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 加密openid
            encrypted_openid = encrpty_openid(openid)
            return render(request, 'oauth_callback.html', context={'encrypted_openid': encrypted_openid})
        else:
            # 用户存在，说明用户绑定过，直接登陆
            login(request, qquser.user)
            # 设置cookie信息
            response = redirect(reverse('contents:index'))
            response.set_cookie(
                'username', qquser.user.username, max_age=14*24*3600)
            return response

    def post(self, request):
        """QQ登陆，未绑定过个人信息"""
        # 获取数据
        mobile = request.POST.get('mobile')
        password = request.POST.get('password')
        sms_code = request.POST.get('sms_code')
        encrypted_openid = request.POST.get('encrypted_openid')

        # 校验参数
        # 判断参数是否齐全
        if not all([mobile, password, sms_code]):
            return HttpResponseBadRequest('缺少必传参数')
        # 判断手机号是否合法
        from re import match
        if not match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseBadRequest('请输入正确的手机号码')
        # 判断密码是否合格
        if not match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseBadRequest('请输入8-20位的密码')
        # 判断短信验证码是否一致
        from django_redis import get_redis_connection
        redis_conn = get_redis_connection('code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if sms_code_server is None:
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '无效的短信验证码'})
        if sms_code != sms_code_server.decode():
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '输入短信验证码有误'})
        # 判断openid是否有效：错误提示放在sms_code_errmsg位置
        openid = check_access_token(encrypted_openid)
        if not openid:
            return render(request, 'oauth_callback.html', {'openid_errmsg': '无效的openid'})
        
        from apps.users.models import User
        try:
            # 判断该手机号是否注册过
            user = User.objects.get('mobile')
        except User.DoesNotExist:
            # 手机号未注册过，则创建用户
            user = User.objects.create_user(
                username = mobile,
                password = password,
                mobile = mobile
            )
        else:
            # 手机号注册过，绑定数据
            # 判断密码是否正确
            if not user.check_password(password):
                return HttpResponseBadRequest('该手机号已被注册，且密码错误')

        # 绑定openid
        from apps.oauth.models import OAuthQQUser
        OAuthQQUser.objects.create(
            user = user,
            openid = openid
        )
        login(request, user)
        response =  redirect(reverse('contents:index'))
        response.set_cookie(
                'username', user.username, max_age=14*24*3600)
        return response